import docx  # 读取docx文件库（需提前安装：pip install python-docx）
import os
from pypinyin import lazy_pinyin, Style
from config import Config
from global_vars import global_vars
from datetime import datetime

class TextProcessor:
    def __init__(self):
        self.progress_callback = None  # 进度回调函数（更新UI进度条）

    def set_progress_callback(self, callback):
        """设置进度回调函数（供UI调用）"""
        self.progress_callback = callback

    def read_file(self, file_path):
        """
        读取txt/docx文件内容
        :param file_path: 文件路径
        :return: 文件内容字符串，失败返回空字符串
        """
        try:
            if file_path.endswith(".txt"):
                # 读取txt文件（UTF-8编码）
                with open(file_path, "r", encoding="utf-8") as f:
                    return f.read()
            elif file_path.endswith(".docx"):
                # 读取docx文件（使用python-docx库）
                doc = docx.Document(file_path)
                content = "\n".join([para.text for para in doc.paragraphs])
                return content
            else:
                return ""
        except Exception as e:
            print(f"读取文件失败：{e}")
            return ""

    def process_text(self, content):
        # 按段落拆分文本（保留原文换行）
        paragraphs = content.split('\n')
        result = []
        for para in paragraphs:
            para = para.strip()
            if not para:
                continue  # 跳过空行
            # 转换当前段落为拼音
            para_result = self._process_paragraph(para)
            result.extend(para_result)
            result.append({"char": "\n", "pinyin": "\n"})  # 段落间换行
        return result

    def _process_paragraph(self, para):
        # 处理单个段落的拼音转换
        para = para.replace(" ", "")  # 去除段落内空格
        pinyin_list = lazy_pinyin(para, style=Style.TONE)
        return [{"char": char, "pinyin": pinyin} for char, pinyin in zip(para, pinyin_list)]

    def format_result_for_display(self, result):
        if not result:
            return ""
        char_lines = []
        pinyin_lines = []
        current_char_line = ""
        current_pinyin_line = ""
        max_line_length = 30  # 每行最多30个汉字

        for item in result:
            char = item["char"]
            pinyin = item["pinyin"]

            # 处理换行符：结束当前行，开始新行
            if char == "\n":
                if current_char_line or current_pinyin_line:
                    char_lines.append(current_char_line)
                    pinyin_lines.append(current_pinyin_line)
                current_char_line = ""
                current_pinyin_line = ""
                continue

            # 处理特殊符号（用全角空格占位，确保宽度一致）
            if char in ["【", "】"]:
                pinyin_padded = chr(12288) * 6  # 6个全角空格，固定宽度
                char_display = char + chr(12288)
            elif char in ["，", "。", "、"]:
                pinyin_padded = chr(12288) * 6  # 6个全角空格，固定宽度
                char_display = char + chr(12288)
            else:
                # 拼音固定为6个字母长度（用半角空格补齐）
                space_count = max(0, 6 - len(pinyin))
                pinyin_padded = pinyin + " " * space_count
                # 汉字固定为2个全角空格宽度
                char_display = char + chr(12288) * 2

            # 拼接当前行（超过长度则换行）
            if len(current_char_line) + len(char_display) > max_line_length:
                char_lines.append(current_char_line)
                pinyin_lines.append(current_pinyin_line)
                current_char_line = char_display
                current_pinyin_line = pinyin_padded
            else:
                current_char_line += char_display
                current_pinyin_line += pinyin_padded

        # 拼接最后一行
        if current_char_line:
            char_lines.append(current_char_line)
            pinyin_lines.append(current_pinyin_line)

        # 组合“拼音行 + 汉字行”，并去除首尾多余空格
        display_str = ""
        for p_line, c_line in zip(pinyin_lines, char_lines):
            p_line_stripped = p_line.strip()
            c_line_stripped = c_line.strip()
            display_str += p_line_stripped + "\n" + c_line_stripped + "\n\n"
        return display_str

    def add_history(self, content, record_type):
        """添加历史记录（同单字处理器的add_history，可抽离为公共函数）"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        record = {
            "type": record_type,
            "content": content,
            "time": current_time
        }
        global_vars.history_records.insert(0, record)
        if len(global_vars.history_records) > 10:
            global_vars.history_records.pop()